<template>
  <div class="tab_content">
    <!-- 操作按钮区域 -->
    <div class="common_button flex_ac margin_t20">
      <div class="right_button flex">
        <a href="javascript:;" class="color_blue" @click="handleAdd">
          <img class="btn_img" src="@/assets/pinggu/add.png" alt="">新建
        </a>
      </div>
    </div>

    <!-- 评委列表表格 -->
    <div class="common_block_div">
      <el-table v-loading="judgeLoading" :data="judgeList" style="width: 100%">
        <el-table-column label="集合编号" align="center" prop="id" />
        <el-table-column label="评委姓名" align="center" prop="nickname" />
        <el-table-column label="登录账号" align="center" prop="name" />
        <el-table-column label="已完成评分" align="center" prop="has_complate" />
        <el-table-column label="操作" align="center" width="280" fixed="right">
          <template slot-scope="scope">
            <!-- <el-button type="text" size="mini" @click="handleView(scope.row)">查看</el-button> -->
            <el-button type="text" size="mini" @click="handleJudgeEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="mini" style="color: #F56C6C;" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>

    <!-- 查看评委详情弹框 -->
    <el-dialog v-dialogDrag :close-on-click-modal="false" title="评委详情" :visible.sync="detailVisible"
      width="600px" append-to-body @closed="handleDetailClosed">
      <div v-loading="detailLoading" class="detail-content">
        <el-form :model="detailData" label-width="100px">
          <el-form-item label="项目">
            <el-input :value="projectName" disabled style="width: 100%" />
          </el-form-item>
          <el-form-item label="集合编号">
            <el-input :value="detailData.id || ''" disabled style="width: 100%" />
          </el-form-item>
          <el-form-item label="评委姓名">
            <el-input :value="detailData.nickname || ''" disabled style="width: 100%" />
          </el-form-item>
          <el-form-item label="登录账号">
            <el-input :value="detailData.name || ''" disabled style="width: 100%" />
          </el-form-item>
          <el-form-item label="已完成评分">
            <el-input :value="(detailData.has_complate || 0) + ' 项'" disabled style="width: 100%" />
          </el-form-item>
          <el-form-item label="评分进度">
            <el-progress :percentage="detailData.scoring_progress || 0"
              :status="getProgressStatus(detailData.scoring_progress)" style="width: 100%"></el-progress>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加/编辑评委弹框 -->
    <el-dialog v-dialogDrag :close-on-click-modal="false" :title="formDialogTitle" :visible.sync="formVisible"
      width="600px" append-to-body @closed="handleFormClosed">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="项目">
          <el-input :value="projectName" disabled style="width: 100%" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="formData.nickname" placeholder="请输入昵称" maxlength="50" clearable />
        </el-form-item>
        <el-form-item label="登录账号" prop="name">
          <el-input v-model="formData.name" placeholder="请输入登录账号（手机号）" maxlength="20" clearable />
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input v-model="formData.password" type="password" placeholder="请输入登录密码" show-password maxlength="20"
            clearable />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="formSubmitting">
          {{ formSubmitting ? '提交中...' : '确 定' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入评委管理API
import judgeApi from "@/api/judge";

export default {
  name: 'JudgeSetting',
  props: {
    projectId: {
      type: String,
      default: ''
    },
    projectName: {
      type: String,
      default: ''
    },
    http: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      judgeLoading: false,
      judgeList: [],
      // 查看详情弹框相关
      detailVisible: false,
      detailLoading: false,
      detailData: {},
      // 添加/编辑弹框相关
      formVisible: false,
      formDialogTitle: '新增评委',
      formSubmitting: false,
      formData: {
        id: '',
        project_id: '',
        name: '',
        nickname: '',
        password: ''
      },
      // formRules 改为计算属性，以便动态显示必填标识
    }
  },
  computed: {
    formRules() {
      // 判断是否是编辑模式
      const isEditMode = !!this.formData.id;
      
      return {
        name: [
          { required: true, message: '请输入登录账号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        password: [
          {
            required: !isEditMode, // 新增时必填（显示星号），编辑时不必填
            validator: (rule, value, callback) => {
              // 如果是编辑模式（有id），密码可选；如果是新增模式，密码必填
              const isEdit = this.formData.id;
              
              if (!value) {
                // 编辑模式下密码可以为空
                if (isEdit) {
                  callback();
                } else {
                  // 新增模式下密码必填
                  callback(new Error('请输入登录密码'));
                }
              } else if (value.length < 6) {
                callback(new Error('密码长度不能少于6位'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ]
      };
    }
  },
  methods: {
    /** 获取评委列表 */
    getJudgeList() {
      const _this = this;
      if (!this.projectId) {
        this.judgeLoading = false;
        this.judgeList = [];
        return;
      }
      this.judgeLoading = true;

      // 构建查询参数
      const params = {
        project_id: this.projectId
      };

      // 调用API获取评委列表，直接使用 res.message 作为列表数据
      judgeApi.list(params).then(function (res) {
        if (res && res.message) {
          // 直接使用 res.message，如果是数组则直接使用，否则使用空数组
          _this.judgeList = Array.isArray(res.message) ? res.message : [];
        } else {
          _this.judgeList = [];
        }
        _this.judgeLoading = false;
      }).catch(function (error) {
        console.error('获取评委列表失败:', error);
        _this.judgeList = [];
        _this.judgeLoading = false;
      });
    },
    /** 新增评委 */
    handleAdd() {
      this.resetForm();
      // 使用外部传入的projectId
      this.formData.project_id = this.projectId || '';
      this.formDialogTitle = '新增评委';
      this.formVisible = true;
    },

    /** 编辑评委 */
    handleJudgeEdit(row) {
      const _this = this;
      if (!row.id) {
        this.$message.warning('无法编辑该数据');
        return;
      }

      // 重置表单
      this.resetForm();
      this.formDialogTitle = '编辑评委';

      // 调用API获取详情数据，需要传递 project_id
      judgeApi.detail({ id: row.id, project_id: this.projectId }).then((res) => {
        if (res && res.message) {
          _this.formData = {
            id: res.message.id || '',
            project_id: res.message.project_id || _this.projectId || '',
            name: res.message.name || '',
            nickname: res.message.nickname || '',
            password: ''
          };
          _this.formVisible = true;
        } else {
          _this.$message.error('获取详情失败');
        }
      }).catch((error) => {
        console.error('获取详情失败:', error);
        _this.$message.error('获取详情失败');
      });
    },

    /** 重置表单 */
    resetForm() {
      this.formData = {
        id: '',
        project_id: this.projectId || '',
        name: '',
        nickname: '',
        password: ''
      };
      if (this.$refs.formRef) {
        this.$refs.formRef.clearValidate();
      }
    },

    /** 表单弹框关闭后的回调 */
    handleFormClosed() {
      this.resetForm();
    },

    /** 提交表单 */
    handleSubmit() {
      const _this = this;
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.formSubmitting = true;

          // 构建提交数据
          const submitData = {
            name: this.formData.name,
            nickname: this.formData.nickname || '',
            project_id: this.formData.project_id || this.projectId
          };

          // 如果是编辑，需要传id
          if (this.formData.id) {
            submitData.id = this.formData.id;
          }

          // 只有在密码有值时才传递密码字段（编辑时密码可以为空）
          if (this.formData.password) {
            submitData.password = this.formData.password;
          }

          // 调用API创建或更新
          judgeApi.createOrUpdate(submitData).then((res) => {
            if (res) {
              _this.$message.success(this.formData.id ? '修改成功' : '添加成功');
              _this.formVisible = false;
              _this.getJudgeList();
            }
            _this.formSubmitting = false;
          }).catch((error) => {
            console.error('提交失败:', error);
            _this.$message.error('提交失败');
            _this.formSubmitting = false;
          });
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },

    /** 删除评委 */
    handleDelete(row) {
      const _this = this;
      if (!row.id) {
        this.$message.warning('无法删除该数据');
        return;
      }
      this.$confirm('确定要删除该评委吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用删除API，需要传递 project_id
        judgeApi.delete({ id: row.id, project_id: this.projectId }).then((res) => {
          if (res) {
            _this.$message.success('删除成功');
            _this.getJudgeList();
          }
        }).catch((error) => {
          console.error('删除失败:', error);
          _this.$message.error('删除失败');
        });
      }).catch(() => {
        // 用户取消删除
      });
    },

    /** 查看评委详情 */
    handleView(row) {
      const _this = this;
      if (!row.id) {
        this.$message.warning('无法查看该数据');
        return;
      }

      // 打开详情弹框
      this.detailVisible = true;
      this.detailLoading = true;
      this.detailData = {};

      // 调用API获取评委详情，需要传递 project_id
      judgeApi.detail({ id: row.id, project_id: this.projectId }).then((res) => {
        if (res && res.message) {
          _this.detailData = {
            id: res.message.id || '',
            nickname: res.message.nickname || '',
            name: res.message.name || '',
            has_complate: res.message.has_complate || 0,
            scoring_progress: res.message.scoring_progress || 0
          };
        } else {
          _this.$message.error('获取详情失败');
          _this.detailVisible = false;
        }
        _this.detailLoading = false;
      }).catch((error) => {
        console.error('获取详情失败:', error);
        _this.$message.error('获取详情失败');
        _this.detailLoading = false;
        _this.detailVisible = false;
      });
    },

    /** 详情弹框关闭后的回调 */
    handleDetailClosed() {
      this.detailData = {};
    },
    getProgressStatus(progress) {
      if (progress >= 100) {
        return 'success';
      } else if (progress >= 50) {
        return '';
      } else {
        return 'exception';
      }
    }
  },
  mounted() {
    this.getJudgeList();
  },
  watch: {
    projectId() {
      this.getJudgeList();
    }
  }
}
</script>

<style scoped>
.tab_content {
  min-height: 300px;
}
</style>
